package com.cby.android.sample.activities

import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.cby.android.library.base.BaseStateActivity
import com.cby.android.library.ext.observe
import com.cby.android.sample.R
import com.cby.android.sample.adapter.RollCommonQueryAdapter
import com.cby.android.sample.bean.roll.RollCommonBean
import com.cby.android.sample.intent.RollMoreIntent
import com.cby.android.sample.model.RollMoreViewModel
import com.cby.android.sample.state.RollMoreState
import com.scwang.smart.refresh.layout.api.RefreshLayout
import kotlinx.coroutines.launch

/**
 * @description: RollWorldPhoneCodeActivity
 *
 * @author ChenBaoyang
 * @date 4/24/21 10:13
 */
class RollWorldPhoneCodeActivity : BaseStateActivity<RollMoreViewModel, RollMoreState, RollMoreIntent>() {

    private val refreshLayout: RefreshLayout by lazy { findViewById(R.id.refreshLayout) }
    private val recyclerView: RecyclerView by lazy { findViewById(R.id.recycler_view) }
    private lateinit var adapter: RollCommonQueryAdapter

    override fun bindLiveData() {
        observe(viewModel!!.state) {

            val datas = mutableListOf<RollCommonBean>()
            for (i in it.dataPhoneCodes.indices) {
                val commonBean = RollCommonBean("${it.dataPhoneCodes[i].zhCn} ( + ${it.dataPhoneCodes[i].enUs} + )",
                    it.dataPhoneCodes[i].phoneCode)
                datas.add(commonBean)
            }
            adapter.setNewData(datas)
        }
    }

    override fun reload() {
        lifecycleScope.launch {
            viewModel!!.intents.send(RollMoreIntent.LoadRollPhoneIntent)
        }
    }

    override fun getLayoutId() = R.layout.common_activity_recycler_view

    override fun onViewInit() {
        title = "世界电话区号"
        refreshLayout.setEnableRefresh(false)
        refreshLayout.setEnableLoadMore(false)
        val linearLayoutManager =
            LinearLayoutManager(
                this,
                LinearLayoutManager.VERTICAL,
                false
            )
        recyclerView.layoutManager = linearLayoutManager
        recyclerView.itemAnimator = DefaultItemAnimator()

        adapter = RollCommonQueryAdapter(R.layout.roll_item_common_query2)
        recyclerView.adapter = adapter
    }

    override fun onDataInit() {
        super.onDataInit()
        reload()
    }


    override fun getTargetView() = refreshLayout
}